/**
 * Created with JetBrains PhpStorm.
 * User: laice
 * Date: 8/31/13
 * Time: 3:44 AM
 *
 */

var http = require('http'),
    fs = require('fs'),
    events = require('events'),
    mongoose = require('mongoose'),
    format = require('util').format,
    less = require('less'),
    opt = require('./opt.js'),
    config = require('./config.js');

var page_body = "";
var c_css;
var ind;
var irc_data = new Array();
var mrp = new Array();
var found_player;

var wins;
var losses;
var wins2;
var losses2;
var name;
var name2;
var apikey;
var apikey2;
var p1_curr;
var p2_curr;
var p1_prev;
var p2_prev;

var p1_finding = "";
var p2_finding = "";
var finding_players = new events.EventEmitter();
var salt_last_mod;
var pepper_first_half;

var player1_temp;
var player2_temp;

function update_css() {

    fs.readFile('./styles.less', { encoding: 'utf8'}, function (err, lcss) {
        less.render(lcss, function( e, css) {
            //if (e) { throw e; }
            //console.log("rendering less");
            c_css = css;
        })

    });

    return c_css

}


function update_index() {
    //console.log(Date.now() + " updating index ")
    /*
    Index.find(function(err, indexes) {
        if (err) { throw err;}
        if ( is_empty(indexes)) {
            index.save(function(err, index) {
                if (err) { throw err;}
               // console.log(index.title + " saved")
            })
        }
    });
     */
    top_six_pgs();


    ind = index.inject_page(page_body, c_css)
    update_css()

    return ind
}

setInterval(update_index, 10000)

function update_salt() {
    if(server.started) {
        salty_req();

    }

}

setInterval(update_salt, 10000)
/*
fs.readFile('./styles.less', { encoding: 'utf8'}, function (err, lcss) {

    if (err) {
        throw err;
    }

    var c_css
    less.render(lcss, function( e, css) {
        if (e) { throw e; }
        console.log("rendering less")
        c_css = css
    })
*/
var server = http.createServer(
    /*{
        key: fs.readFileSync('server-key.pem'),
        cert: fs.readFileSync('server-cert.pem')
    },
    */

    function (request, response) {
        update_index()
        console.log('request received for url: ' + request.url);
        //console.log(request);
        response.writeHead(200, {'Content-Type': 'text/html'});
        //var msg = info.build_message()
        if (request.url == '/start') {
          console.log('url /start found');
          parse_irc_log();
          salty_req();
          this.started = true;

        } else if (request.url =='/upd') {
            console.log('url /upd found')
        }
        //response.write();
        response.end(ind);

        //response.end(html);


       /* var c_options = {
            hostname:'www.google.com',
            port: 80,
            method: 'GET'
        };

        var c_req = http.request(c_options,
            function(res) {
                res.on('data', function(data) {
                    console.log( data.toString() );
                });
            }
        );
        c_req.on('error', function(e) {
            console.log('problem with request: ' + e.message);
        });
        //c_req.write('data\n');
        //c_req.write('data\n');



        c_req.end();
        */

    }

).listen(8080);

var salt_schema = mongoose.Schema({
    last_modified: String,//{type: String, unique: true, dropDups: true},
    expires: String, //{type: String, unique: true, dropDups: true},
    prev_data: String, //{type: String, unique: true, dropDups: true},
    curr_data: String//{type: String, unique: true, dropDups: true},

});

salt_schema.methods.get_data = function() {
    var data = { r_data: this.r_data, p_data: this.p_data, last_modified: this.last_modified }

    return data;
}


function salty_req() {

    //console.log("salty request init")


        if(is_empty(salt_last_mod)) {
            http.get("http://www.saltybet.com/state.json", function(res) {
                console.log("Got response: " + res.statusCode);
                for(var i in res.headers) {
                    if( i == "last-modified") salt_last_mod = res.headers[i];
                }
                res.setEncoding('utf8');
                res.on('data', function(data) {
                    // do stuff with salty bet data here

                    var a = data.substring(0,15)
                    if( a == "<!DOCTTYPE html>"){
                         console.log("salty_req received html page");
                    } else {
                        console.log('data: ' + data);
                    }


                });


            }).on('error', function(e) {
                    console.log("Initial state.json request error: " + e.message);

                });
        } else {

            var options = {
                hostname:'www.saltybet.com',
                port:80,
                path:'/state.json',
                headers: {
                    'If-Modified-Since': salt_last_mod
                }
            }
            http.get(options, function(res){
                for(var i in res.headers) {
                    if(i == 'last-modified') salt_last_mod = res.headers[i];

                }
                res.on('data', function(data){
                   console.log("data: " + data)
                });
            }).on('error', function(e) {
                    console.log('main state.json request error: ' + e.message);
                })
        }
}

function pepper_req(champ_one, champ_two) {
    var s = "http://www.apeppershaker.com/api/fights/by_name/" + champ_one + "/" + champ_two;


    console.log("in pepper_req")

    http.get(s,function (res) {
        //console.log("Got response: " + res.statusCode);
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            // do stuff with pepper match data here
            var ss = chunk.substring(chunk.length-1);
            var s;
            if (ss!="}"){
                console.log("pepper_first_half needed");
                pepper_first_half = chunk;
                return;
            } else if ( ss == "}") {

                if(!is_empty(pepper_first_half)){
                    s = pepper_first_half + chunk;
                    pepper_first_half = null;

                } else {
                    s = chunk;
                }
                //console.log(s);

            }

            if(!is_empty(s)) {
                // we have a good data chunk now, hopefully
                // var data = JSON.parse(s);
                // console.log(data);

                parse_pepper_json(s, 2);
            }
            //console.log("chunk ss: " + ss);

        });
    }).on('error', function (e) {
            console.log("Got error: " + e.message);
        });
};

function pepper_req_single(id, slot){
    var s = "http://apeppershaker.com/api/champions/" + id;

    http.get(s, function(res) {
        res.setEncoding('utf8')

        res.on('data', function(data) {
            console.log("single pepper req data: " + data);

            parse_pepper_json(data, 1, slot)
        })

    }).on('error', function(err) {
        throw err;
    });


}

function match_players(p1, p2) {
    console.log("matching players") //p1 : " + p1 + " p2 : " + p2);
    var s1, s2, s;
    Listing.find({title : p1.name}, function(err, listings) {
        if(err) throw err;
        if(!is_empty(listings)) {
            console.log("Listings :" + listings);
        }
    });
}

function parse_pepper_json(data, one_or_two, slot) {
    var pat
    if(one_or_two == 2) {
        pat = /\{"(left)":\{"id":(\d+),"name":"(.+)","elo":(\d+),"wins":(\d+),"losses":(\d+),"aggression_index":([\d\w]+),"total_bets":(\d+),"created_at":"(.+)","updated_at":"(.+)","gets_hitboxed":([\d\w]+),"undersized_hitbox":([\d\w]+),"oversized_hitbox":([\d\w]+),"zoning":([\d\w]+),"rushdown":([\d\w]+),"one_hit_knockout":([\d\w]+),"doesnt_super":([\d\w]+),"high_health":([\d\w]+),"low_health":([\d\w]+),"high_damage":([\d\w]+),"low_damage":([\d\w]+),"grappler":([\d\w]+),"grapple_immune":([\d\w]+),"flies":([\d\w]+),"heals":([\d\w]+),"timescammer":([\d\w]+),"has_fakes":([\d\w]+),"bad_ai":([\d\w]+)\},"(right)":\{"id":(\d+),"name":"(.+)","elo":(\d+),"wins":(\d+),"losses":(\d+),"aggression_index":([\d\w]+),"total_bets":(\d+),"created_at":"(.+)","updated_at":"(.+)","gets_hitboxed":([\d\w]+),"undersized_hitbox":([\d\w]+),"oversized_hitbox":([\d\w]+),"zoning":([\d\w]+),"rushdown":([\d\w]+),"one_hit_knockout":([\d\w]+),"doesnt_super":([\d\w]+),"high_health":([\d\w]+),"low_health":([\d\w]+),"high_damage":([\d\w]+),"low_damage":([\d\w]+),"grappler":([\d\w]+),"grapple_immune":([\d\w]+),"flies":([\d\w]+),"heals":([\d\w]+),"timescammer":([\d\w]+),"has_fakes":([\d\w]+),"bad_ai":([\d\w]+)\}\}/;

        var p_d = pat.exec(data);

        if(!is_empty(p_d)) {
            var total1 = p_d[5] + p_d[6]
            var total2 = p_d[33] + p_d[34]
            var win1;
            var win2;
            if(p_d[5] == 0) win1 = -1;
            if(p_d[33] == 0) win2 = -1;

            var p1 = total1/win1;
            var p2 = total2/win2;

            var attributes_p1 = {
                id : p_d[2],
                elo : p_d[4],
                aggression_index : p_d[7],
                total_bets : p_d[8],
                created_at : p_d[9],
                updated_at : p_d[10],
                gets_hitboxed : p_d[11],
                undersized_hitbox : p_d[12],
                oversized_hitbox : p_d[13],
                zoning: p_d[14],
                rushdown: p_d[15],
                one_hit_knockout: p_d[16],
                doesnt_super: p_d[17],
                high_health: p_d[18],
                low_health: p_d[19],
                high_damage: p_d[20],
                low_damage: p_d[21],
                grappler: p_d[22],
                grapple_immune: p_d[23],
                flies: p_d[24],
                heals: p_d[25],
                timescammer: p_d[26],
                has_fakes: p_d[27],
                bad_ai: p_d[28]
            }

            var attributes_p2 = {
                id : p_d[30],
                elo : p_d[32],
                aggression_index : p_d[35],
                total_bets : p_d[36],
                created_at : p_d[37],
                updated_at : p_d[38],
                gets_hitboxed : p_d[39],
                undersized_hitbox : p_d[40],
                oversized_hitbox : p_d[41],
                zoning: p_d[42],
                rushdown: p_d[43],
                one_hit_knockout: p_d[44],
                doesnt_super: p_d[45],
                high_health: p_d[46],
                low_health: p_d[47],
                high_damage: p_d[48],
                low_damage: p_d[49],
                grappler: p_d[50],
                grapple_immune: p_d[51],
                flies: p_d[52],
                heals: p_d[53],
                timescammer: p_d[54],
                has_fakes: p_d[55],
                bad_ai: p_d[56]
            }

            var p1_name = p_d[3],
                p1_wins =       "Wins......." + p_d[5],
                p1_losses =     "Losses....." + p_d[6],
                p1_e =          "E-rating..." + p_d[4],
                p1_tb =         "Total Bets." + p_d[8],
                p1_id =         "ID........." + p_d[2],
                p2_name = p_d[31],
                p2_wins =       "Wins......." + p_d[33],
                p2_losses =     "Losses....." + p_d[34],
                p2_e =          "E-rating..." + p_d[32],
                p2_tb =         "Total Bets." + p_d[36],
                p2_id =         "ID........." + p_d[30];


            var body =
                "<div id='player_one'>" +
                    "<div id='name'>" +
                        "(" + p2_id + ")" + p1_name +
                    "</div>" +
                    "<div id='wins'>" +
                         p1_wins +
                    "</div>" +
                    "<div id='losses'>" +
                         p1_losses +
                    "</div>" +
                    "<div id='e'>" +
                        p1_e +
                    "</div>" +
                    "<div id='total_bets'>" +
                        p1_tb +
                    "</div>" +
                "</div>" +
                "<div id='player_two'>" +
                    "<div id='name'>" +
                        "("+ p2_id +")  " + p2_name +
                    "</div>" +
                    "<div id='wins'>" +
                         p2_wins +
                    "</div>" +
                    "<div id='losses'>" +
                        p2_losses +
                    "</div>" +
                    "<div id='e'>" +
                        p2_e +
                    "</div>" +
                    "<div id='total_bets'>" +
                        p2_tb +
                    "</div>" +
                "</div>";


            var title = p1_name + " versus " + p2_name;
            var author = "infopunk scraper"


            page_maker(title, author, body);

            add_player(p1_name,p_d[5],p_d[6], p1, p_d[4], total1, null, attributes_p1);
            add_player(p2_name,p_d[33],p_d[34], p2, p_d[32], total2, null, attributes_p2);
            //add_player(p_d[32],p_d[33],p_d[34], p2, p_d[32], total2, p_d[30], attributes_p2);


            //console.log(p_d);
        }
    } else if ( one_or_two == 1) {
        pat = /\{"id":(\d+),"name":"(.+)","elo":(\d+),"wins":(\d+),"losses":(\d+),"aggression_index":([\d\w]+),"total_bets":(\d+),"created_at":"(.+)","updated_at":"(.+)","gets_hitboxed":([\d\w]+),"undersized_hitbox":([\d\w]+),"oversized_hitbox":([\d\w]+),"zoning":([\d\w]+),"rushdown":([\d\w]+),"one_hit_knockout":([\d\w]+),"doesnt_super":([\d\w]+),"high_health":([\d\w]+),"low_health":([\d\w]+),"high_damage":([\d\w]+),"low_damage":([\d\w]+),"grappler":([\d\w]+),"grapple_immune":([\d\w]+),"flies":([\d\w]+),"heals":([\d\w]+),"timescammer":([\d\w]+),"has_fakes":([\d\w]+),"bad_ai":([\d\w]+)\}/;

        var p_d = pat.exec(data);

        if(!is_empty(p_d)) {
            var total1 = p_d[4] + p_d[5];
            var win1;

            if(p_d[4] == 0) win1 = -1;

            var p1 = total1/win1;


            var attributes_p1 = {
                id : p_d[2],
                elo : p_d[4],
                aggression_index : p_d[7],
                total_bets : p_d[8],
                created_at : p_d[9],
                updated_at : p_d[10],
                gets_hitboxed : p_d[11],
                undersized_hitbox : p_d[12],
                oversized_hitbox : p_d[13],
                zoning: p_d[14],
                rushdown: p_d[15],
                one_hit_knockout: p_d[16],
                doesnt_super: p_d[17],
                high_health: p_d[18],
                low_health: p_d[19],
                high_damage: p_d[20],
                low_damage: p_d[21],
                grappler: p_d[22],
                grapple_immune: p_d[23],
                flies: p_d[24],
                heals: p_d[25],
                timescammer: p_d[26],
                has_fakes: p_d[27],
                bad_ai: p_d[28]
            }

            var p1_name = p_d[2],
                p1_wins =       "Wins......." + p_d[4],
                p1_losses =     "Losses....." + p_d[5],
                p1_e =          "E-rating..." + p_d[3],
                p1_tb =         "Total Bets." + p_d[7],
                p1_id =         "ID........." + p_d[1];



            var body =
                "<div id='name'>" +
                    "(" + p1_id + ")  " + p1_name +
                "</div>" +
                "<div id='wins'>" +
                    p1_wins +
                "</div>" +
                "<div id='losses'>" +
                    p1_losses +
                "</div>" +
                "<div id='e'>" +
                    p1_e +
                "</div>" +
                "<div id='total_bets'>" +
                    p1_tb +
                "</div>";


            var title = p1_name;
            var author = "infopunk scraper"


            listing_maker(title, author, body);
            if(slot) add_player(p1_name,p_d[4],p_d[5], p1, p_d[3], total1, null, attributes_p1, slot);
            else add_player(p1_name,p_d[4],p_d[5], p1, p_d[3], total1, null, attributes_p1);
        }
    }

}

var player_schema = mongoose.Schema({
    name: {type: String}, //unique: true, dropDups: true},
    wins: {type: Number}, //unique: true, dropDups: true},
    losses: {type: Number}, //unique: true, dropDups: true},
    total: {type: Number}, //unique: true, dropDups: true},
    apikey: {type: Number}, //unique: true, dropDups: true},
    percent: {type: Number}, //unique: true, dropDups: true},
    e: {type: Number}, //unique: true, dropDups: true},
    aggression_index: {type: String}, //unique:true, dropDups: true},
    total_bets: {type: String}, //unique:true, dropDups: true},
    created_at: {type: String}, //unique:true, dropDups: true},
    updated_at: {type: String}, //unique:true, dropDups: true},
    gets_hitboxed: {type: String}, //unique:true, dropDups: true},
    undersized_hitbox: {type: String}, //unique:true, dropDups: true},
    oversized_hitbox: {type: String}, //unique:true, dropDups: true},
    zoning: {type: String}, //unique:true, dropDups: true},
    rushdown: {type: String}, //unique:true, dropDups: true},
    one_hit_knockout: {type: String}, //unique:true, dropDups: true},
    doesnt_super: {type: String}, //unique:true, dropDups: true},
    high_health: {type: String}, //unique:true, dropDups: true},
    low_health: {type: String}, //unique:true, dropDups: true},
    high_damage: {type: String}, //unique:true, dropDups: true},
    low_damage: {type: String}, //unique:true, dropDups: true},
    grappler: {type: String}, //unique:true, dropDups: true},
    grapple_immune: {type: String}, //unique:true, dropDups: true},
    flies: {type: String}, //unique:true, dropDups: true},
    heals: {type: String}, //unique:true, dropDups: true},
    timescammer: {type: String}, //unique:true, dropDups: true},
    has_fakes: {type: String}, //unique:true, dropDups: true},
    bad_ai: {type: String}, //unique:true, dropDups: true},
    comments: {type: String} //unique: true, dropDups: true}

});

player_schema.methods.findPlayer = function(cb) {
    return this.model('Player').find({ name: this.name }, cb);
}

player_schema.methods.build_message = function() {


    var s = "<div id='msg_player'> <div id='player_name'>" + this.name + "</div> <br />" +
        "<div id='player_wins'> Wins " + this.wins + "</div><br />" +
        "<div id='player_loss'> Losses " + this.losses + "</div><br /> " +
        "<div id='player_p'> Percent " + this.percent + "</div><br/> " +
        "<div id='player_e'>" + this.e + "</div><br/>" +
        "<div id='msg_comments'>"+ this.comments + "</div></div>";

    return s;
}
/*
var single_find_trigger = function(name, num) {
    if(num == 1) p1_finding = name;
    else if(num == 2) p2_finding = name;

    console.log("FINDING " + name + " for slot " + num);

}
*/
//finding_players.on('finding', single_find_trigger);


function add_player(name, wins, losses, percent, e, total, apikey, attributes, slot) {
    console.log(name + " " + wins + " " + losses + " " + percent + " " + e + " " + total);

    function find_callback(error, results) {
        if(error) console.log("add_player error: " + error);
        var pl;
        if((results[0])) {
            pl = results[0];
        } else {
            pl = new Player();
        }
        //console.log("FIND CALLBACK RESULTS:\n" + results);

        if(name) pl.name = name;
        if(wins) pl.wins = wins;
        if(losses) pl.losses = losses;
        if(apikey) pl.apikey = apikey;
        if(percent) pl.percent = percent;
        if(total) pl.total = total;
        //if(e) pl.e = e;

        var e_ss = e.substr(e.length-1);
        //console.log("E_SS" + e_ss);
        if(e_ss == "-") {pl.e = e.substring(0, e.length-2);}
        else if(e) {pl.e = e;}

        if(attributes) {
            for(var i in attributes) {
                pl[i] =  attributes[i];
            }
        }

        pl.save(function(err, pl) {
            if(err) { throw err; }
            // console.log("FIND CALLBACK SAVE RESULTS:\n" + pl);
            if(slot) {
                if(slot == 1) {
                    player1_temp = pl ;
                } else if(slot == 2) {
                    player2_temp = pl;
                }
           }
        })


        if(name)mrp.name = name;
        if(wins)mrp.wins = wins;
        if(losses)mrp.losses = losses;
        if(percent)mrp.percent = percent;
        if(total)mrp.total = total;
        if(apikey)mrp.apikey = apikey;
        if(attributes){
            for(i in attributes){
                mrp[i] = attributes[i];
            }
        }


    }

   // if(name != p1_finding && name != p2_finding) {
       // finding_players.emit('finding', name, p_num);
        Player.find({ name : name }, find_callback);


  //  }

}

function parse_irc_log() {
    fs = require('fs');
    var path = DATA_FOLDER;
    var salty_files = new Array();
    var ids = new Array();

    fs.readdir(path, function(err, files) {

        for(var i = 0; i < files.length; ++i ) {

            console.log("file " + files[i]);
            var check = files[i].indexOf("#salt");
            if (check != -1 ){
                var file_name = path + files[i];
                fs.readFile(file_name, function(err, data) {
                        console.log("adding salty file");
                        salty_files.push(data);
                        ids.push(file_name);
                        parse_irc_log2(salty_files, ids);

                });
            }



        }

    });



}

function parse_irc_log2(salty_files, ids) {
    console.log("salty file len " + salty_files.length);
    if(salty_files.length == 1){
        var i = 0;
        console.log("loop through salty files");
        var file_name = ids[i];
        var curr_file;
        var prev_file;

        fs.readFile(file_name, {encoding : 'utf8', flag : 'r'}, function(err, data) {
            if(err) throw err;
            console.log("reading file " + file_name);
            curr_file = data.match(/^.*((\r\n|\n|\r)|$)/gm);
            for(var i = 0; i <= curr_file.length-1; i++) {
                if(curr_file[i]) {
                    //parse_irc_line(curr_file[i]);
                    parse_irc_entire_line(curr_file[i]);
                }
            }
        });



        fs.watchFile(file_name,{persistent: true, interval: 500 } ,function(curr, prev) {
            //console.log("watching file");
            if(curr != prev) {
                //console.log("new content");
                fs.readFile(file_name, {encoding : 'utf8', flag : 'r'}, function(err, data) {
                    prev_file = curr_file;
                    //console.log("prev len " + prev_file.length);



                    curr_file = data.match(/^.*((\r\n|\n|\r)|$)/gm);

                    var diff = curr_file.length - prev_file.length;
                    //console.log(diff);

                    if (diff == 1){
                        //console.log(curr_file[curr_file.length-2]);
                        if(curr_file[curr_file.length-2]) {
                            //parse_irc_line(curr_file[curr_file.length-2]);
                            parse_irc_entire_line(curr_file[curr_file.length-2]);
                        }
                    }


                });
            }
        });
    } else {
        for(var i = 0; i < salty_files.length; i++) {
            console.log("loop through salty files");
            var file_name = ids[i];
            var curr_file;
            var prev_file;

            fs.readFile(file_name, {encoding : 'utf8', flag : 'r'}, function(err, data) {
                if(err) throw err;
                console.log("reading file " + file_name);
                curr_file = data.match(/^.*((\r\n|\n|\r)|$)/gm);
                for(var i = 0; i <= curr_file.length-1; i++) {
                    if(curr_file[i]) {
                        //parse_irc_line(curr_file[i]);
                        parse_irc_entire_line(curr_file[i], false);
                    }
                }
            });



            fs.watchFile(file_name,{persistent: true, interval: 500 } ,function(curr, prev) {
                //console.log("watching file");
                if(curr != prev) {
                    //console.log("new content");
                    fs.readFile(file_name, {encoding : 'utf8', flag : 'r'}, function(err, data) {
                        prev_file = curr_file;
                        //console.log("prev len " + prev_file.length);



                        curr_file = data.match(/^.*((\r\n|\n|\r)|$)/gm);

                        var diff = curr_file.length - prev_file.length;
                        //console.log(diff);

                        if (diff == 1){
                            //console.log(curr_file[curr_file.length-2]);
                            if(curr_file[curr_file.length-2]) {
                                //parse_irc_line(curr_file[curr_file.length-2]);
                                parse_irc_entire_line(curr_file[curr_file.length-2], true);
                            }
                        }


                    });
                }
            });
        }
    }
}

function parse_irc_entire_line(line, recent){
    // get rid of whitespace on edges
    // this is an example of what we're parsing:
    //[14:59] <Peppermill> emerald: [E: 580] [16W/5L] (76.2% out of 21) | hebiitigo: [E: -95] [1W/43L] (2.3% out of 44) | HT: http://apeppershaker.com/api/f/1239/345
    var m_pat = /\u005b(\d\d:\d\d)\u005d\s\u003cPeppermill\u003e\s(.*):\s\u005bE:\s([\d\u002d]+)\u005d\s\u005b(\d+)W\u002f(\d+)L\u005d\s\u0028([\d\u002e]+)\u0025\sout\sof\s(\d+)\u0029\s\u007c\s(.*):\s\u005bE:\s([\d\u002d]+)\u005d\s\u005b(\d+)W\u002f(\d+)L\u005d\s\u0028([\d\u002e]+)\u0025\sout\sof\s(\d+)\u0029\s\u007c\sHT:\s(.*)/;
    var a = m_pat.exec(line);

    if(!is_empty(a)) {
        var url = a[14];
        var u_pat = /http:\/\/apeppershaker\.com\/api\/f\/(\d+)\/(\d+)/;
        var u = u_pat.exec(url);
        if(!is_empty(u)) {
            console.log("PARSE IRC ENTIRE LINE OUTPUT: ");
            console.log(a);


            Player.find({name : a[2]}, function(err, results1) {
                if(err) throw err;
                var p1, p2;
                if(!is_empty(results1)) {
                    p1 = true;
                    console.log("results 1: " + results1);
                } else p1 = false;

                Player.find({name : a[8]}, function(err, results2){
                    if(err) throw err;

                    if(!is_empty(results2)) {
                        p2 = true;
                        console.log("results 2: " + results2);
                    } else p2 = false;

                    var p_reqqer = false;

                    if(p1 && p2) {
                        player1_temp = results1;
                        player2_temp = results2;
                    } else if(!p1 && p2){
                        pepper_req_single(u[1], 1);
                        player2_temp = results2;
                    } else if(p1 && !p2) {
                        player1_temp = results1;
                        pepper_req_single(u[2], 2);
                    } else if(!p1 && !p2) {
                        p_reqqer = true;
                        pepper_req(a[2], a[8]);
                    }

                    if(!p_reqqer) {
                        match_players(player1_temp, player2_temp);

                    }

                });


            });





            //pepper_req(a[2],a[8]);
            //add_player(a[2],a[4],a[5],a[6],a[3],a[7], null, 1);
            //add_player(a[8],a[10],a[11],a[12], a[9], a[13], null, 2);
        }
    }





    /*
    var p1 = Player.new();
    p1.name = a[2];
    p1.e = a[3];
    p1.wins = a[4];
    p1.losses = a[5];
    p1.percent = a[6];
    p1.total = a[7];

    var p2 = Player.new();
    p2.name = a[8];
    p2.e = a[9];
    p2.wins = a[10];
    p2.losses = a[11];
    p2.percent = a[12];
    p2.total = a[13];
    */


}



function parse_irc_line(line) {

    var nl = line.trim();
    //console.log(nl);

    var time = parse_irc_timestamp(nl);
   //console.log(time);

    var name = parse_irc_name(nl);
    //console.log(name);

    var msg = parse_irc_msg(nl);
    //console.log(msg);
    if (name){
        if(name[1] === "<Peppermill>") {
           //console.log("got peppermill");
            var msg2 = parse_pepper_msg(line);
            if (msg2) {
                //console.log(msg2);
            }
        }
    }


}

function parse_irc_timestamp(line) {
    var ts_pat = /\u005b\d\d:\d\d\u005d/;
    var time = ts_pat.exec(line);
    var time2 = line.match(ts_pat);
    //console.log(time);
    return time2;
}

function parse_irc_name(line) {
    var n_pat = /(\u003c[\w\d\s\u002d_]+\u003e|\s\u002a\s[\w\d\u002d_]+\s)/;
    var name = n_pat.exec(line);
    var name2 = line.match(n_pat);

    return name2;
}

function parse_irc_msg(line) {
    var m_pat = /(\u003e.+|\s\u002a\s[\w\d\u002d_]+\s.+)/;
    var msg = m_pat.exec(line);
    var msg2 = line.match(m_pat);

    return msg2;
}

function parse_pepper_msg(line) {

    if(line) {
        var m_pat = /\u003e.+/;
        var msg2 = m_pat.exec(line);
        //var msg2 = line.match(m_pat);
        if(msg2){
            //console.log(msg2);
            if(msg2[0]) {
                //console.log(msg2[0]);

                parse_pepper_msg2(msg2[0]);


            }
        }
    }


}

function parse_pepper_msg2(line) {
    console.log(line);



    var p1_name = parse_player_name(1, line);
    var p2_name = parse_player_name(2, line);

    var p1_E = parse_player_rating(1, line);
    var p2_E = parse_player_rating(2, line);

    var p1_W = parse_player_wins(1, line);
    var p2_W = parse_player_wins(2, line);

    var p1_L = parse_player_loss(1, line);
    var p2_L = parse_player_loss(2, line);

    var p1_P = compute_percent(p1_W, p1_L);
    var p2_P = compute_percent(p2_W, p2_L);

    //console.log(p1_P);
    //console.log(p2_P);
    console.log(p1_name + " " + p1_W + " " + p1_L + " " + p1_P + " " + p1_E);
    console.log(p2_name + " " + p2_W + " " + p2_L + " " + p2_P + " " + p2_E);





    //Player.find({ name : p1_name },find_callback);
   // Player.find({ name : p2_name }, find_callback);

    add_player(p1_name, p1_W, p1_L, p1_P, p1_E, null);
    add_player(p2_name, p2_W, p2_L, p2_P, p2_E, null);

    if(p1_curr){p1_prev = p1_curr;}
    if(p2_curr){p1_prev = p1_curr;}

    p1_curr = p1_name;
    p2_curr = p2_name;


    //page_body = page_body + pages[i].build_message() + "<br>"


}


function compute_percent(wins, loss) {
    //console.log(wins + " " + loss)
    wins = parseInt(wins);
    loss = parseInt(loss);

    var total = wins + loss;
    if(total == 0) { total = 1;}
    //console.log(total);
    var percent = wins/total;
   // console.log(percent);
    percent = percent * 100;
    return percent;
}

function parse_player_loss(player, line) {
    var m_pat =  /[\d]+L/g;
    var int_msg;

    if(player == 1){
        var msg = m_pat.exec(line);

        if(msg){ int_msg = msg[0];}
    } else if (player == 2) {
        var msg = m_pat.exec(line);
        var msg2 = m_pat.exec(line);

        if(msg2){
            int_msg = msg2[0];
        }
    }

    if(int_msg){
        int_msg = int_msg.substr(0, int_msg.length-1);
        return int_msg;

    }
}

function parse_player_wins(player, line) {
    var m_pat = /[\d]+W/g;
    var int_msg;

    if(player == 1){
        var msg = m_pat.exec(line);

        if(msg){ int_msg = msg[0];}
    } else if (player == 2) {
        var msg = m_pat.exec(line);
        var msg2 = m_pat.exec(line);

        if(msg2){
            int_msg = msg2[0];
        }
    }

    if(int_msg){
        int_msg = int_msg.substr(0, int_msg.length-1);
        return int_msg;

    }
}

function parse_player_rating(player, line) {
    var m_pat;
    var int_msg;

    m_pat = /:\s\u005bE:\s[\u002d\d]+\u005d/g;
    if(player == 1){
        var msg = m_pat.exec(line);
        //console.log(msg);
        if(msg){
            int_msg = msg[0];
            // console.log(msg1);
        }
    } else if (player == 2) {
        var msg = m_pat.exec(line);
        var msg2 = m_pat.exec(line);

        if(msg2){
            int_msg = msg2[0];
        }
    }

    //console.log(int_msg);
    if(int_msg) {
        int_msg = int_msg.substr(6);
        int_msg = int_msg.substr(0,int_msg.length-1);

        return int_msg;
    }




}

function parse_player_name(player, line) {
    var m_pat;
    if(player == 1){
        m_pat = /\u003e\s[\w\d\s\u002c\u003b\u0028\u0029\u0027\u003a\u002d_\u002e\u005f&*\u0024]+:/;
    } else if (player == 2) {
        m_pat = /\u007c\s[\w\d\s\u002c\u003b\u0028\u0029\u0027\u003a\u002d_\u002e\u005f&*\u0024]+:/;
    }

    var msg = m_pat.exec(line);
    if(msg){
        //console.log(msg);
        var msg1 = msg[0];
        msg1 = msg1.substr(2, msg1.length-3);
        console.log(msg1);
        return msg1
    }
}

mongoose.connect('mongodb://localhost/info');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
db.once('open', function callback() {
   // opened
    console.log('db callback called')
});

var main_schema = mongoose.Schema({
    title: String,
    date: {type: Date, default: Date.now },
    hidden: Boolean

})

main_schema.methods.inject_page = function ( pg, style ){



    var s = "<!DOCTYPE html><html><head><title>" + this.title +
        "</title>" +
        "<link href='http://fonts.googleapis.com/css?family=Lekton:400,700,400italic' rel='stylesheet' type='text/css'>" +
        "<style type='text/css'>" + style  + " </style>" +
        "<script src='less.js' type='text/javascript'></script>" +
       // "<script src='config.js' type = 'text/javascript'></script>" +
       // "<script src='client.js'> type='text/javascript'></script>" +
        "</head>" +
        "<body>" +
            "<div id='header'></div>" +
            "<div id='menu'>" +
                "<div id='update'><a href='/'>Update</a></div>" +
                "<hr id='menu_div'/>" +
                "<div id='start'><a href='/start'>Start</a></div>" +
            "</div>" +
            "<div id='main'>" + pg + "</div>" +
            "<div id='footer'> generated on " + this.date + " </div>" +
        "</body>" +
        "</html>";

    return s;
}

var page_schema = mongoose.Schema({
    title: {type: String, default: 'default title'},
    author: {type: String, default: 'default author'},
    body: {type: String, default: 'default body'},
    comments: [{body: String, date: Date }],
    date: {type: Date, default: Date.now },
    hidden: Boolean
})

page_schema.methods.set_title = function(text) {
    this.title = text;
}

page_schema.methods.set_author = function(text) {
    this.author = text;
}

page_schema.methods.set_body = function(text) {
    this.body = text;
}

page_schema.methods.add_comment = function(text, date) {
    if( date == undefined ) { date = Date.now(); }
    this.comments.push({body: text, date: date})
}

page_schema.methods.hide = function() {
    this.hidden = true;
}

page_schema.methods.show = function() {
    this.hidden = false;
}

page_schema.methods.toggle_hidden = function() {
    if (this.hidden == true) {
        this.hidden = false;
    } else if (this.hidden == false ) {
        this.hidden = true;
    }
}


page_schema.methods.build_message = function() {
    var s = "<div id='msg_main'> <div id='msg_title'>" + this.title + "</div> " + "<div id='msg_author'> posted by " + this.author + " on " + this.date + "</div> <hr style='color:darkgreen;size:2;width:75%;' />" + "<div id='msg_body'>" + this.body + "</div><br/>" + "<div id='msg_comments'>"+ this.comments + "</div></div>";


    return s;
}

var listing_schema = mongoose.Schema({
    title: {type: String, default: 'default title'},
    author: {type: String, default: 'default author'},
    body: {type: String, default: 'default body'},
    comments: [{body: String, date: Date }],
    date: {type: Date, default: Date.now },
    hidden: Boolean
})

var Page = mongoose.model('Page', page_schema);
var Index = mongoose.model('Index', main_schema);
var Player = mongoose.model('Player', player_schema);
var Salt = mongoose.model('Salt', salt_schema);
var Listing = mongoose.model('Listing', listing_schema);




var index = new Index({
    title:'infopunk',
    hidden:false
})

Index.find(function(err, indexes) {
    if (err) { throw err;}
    if ( is_empty(indexes)) {
        index.save(function(err, index) {
            if (err) { throw err;}
            console.log(index.title + " saved")
        })
    }
});

function top_six_pgs() {

    Page.find(function(err, pages) {
        if (err) { throw err;}
        // console.log(typeof pages)
        //console.log("page length " + pages.length)
        page_body = "";
        for( var i = 0; i <= 5 ; i++) {
            //console.log(typeof pages[i])
            if (!is_empty(pages[pages.length-i])) {

                page_body = page_body + "<div id='msg_whole'>" + pages[pages.length-i].build_message() + "</div><br>"
            }
        }

    });

}

top_six_pgs()




function page_maker(title, author, body) {
    var pg = new Page();
    pg.title = title;
    pg.author = author;
    pg.body = body;

    pg.save(function(err, pg) {
        if(err) {throw err;}

       top_six_pgs();
    })
}

function listing_maker(title, author, body) {
    var pg = new Listing();
    pg.title = title;
    pg.author = author;
    pg.body = body;

    pg.save(function(err, pg) {
        if(err) {throw err;}

    })
}
/*
Page.find(function(err, pages) {
    if (err) { throw err;}
    // console.log(typeof pages)
    //console.log("page length " + pages.length)

    for( var i = pages.length; i >= 0; i--) {
        //console.log(typeof pages[i])
        if (!is_empty(pages[i])) {

            page_body = page_body + "<div id='msg_whole'>" + pages[i].build_message() + "</div><br>"
        }
    }

});
 */

var hasOwnProperty = Object.prototype.hasOwnProperty;

function is_empty(obj) {

    // null and undefined are empty
    if (obj == null) return true;
    // Assume if it has a length property with a non-zero value
    // that that property is correct.
    if (obj.length && obj.length > 0)    return false;
    if (obj.length === 0)  return true;

    for (var key in obj) {
        if (hasOwnProperty.call(obj, key))    return false;
    }

    // Doesn't handle toString and toValue enumeration bugs in IE < 9

    return true;
}


console.log('Server running at 127.0.0.1:8080');
update_index();
